import axios from 'axios'
import { Toast } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'

// 创建导航实例
// const navigate = useNavigate()

const instance = axios.create({
  timeout: 7000,
  headers: { 'X-Custom-Header': 'foobar' }
});

// 请求拦截器
instance.interceptors.request.use(config => {
  config.headers.Authorization = localStorage.getItem('token')
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器 - 处理401 token过期
instance.interceptors.response.use(response => {
  return response;
}, error => {
  // 处理401错误
  if (error.response && error.response.status === 401) {
    // 清除过期token
    localStorage.removeItem('token')
    // 清除Redux中的用户信息
    store.dispatch({ type: 'user/clearUserInfo' })
    // 提示并跳转登录页
    Toast.show({
      content: '登录已过期，请重新登录',
      type: 'fail'
    })
    navigate('/login')
  }
  return Promise.reject(error);
});

export default instance